package com.cse.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cse.dto.Result;
import com.cse.entity.VoucherOrder;
import com.cse.mapper.VoucherOrderMapper;
import com.cse.service.ISeckillVoucherService;
import com.cse.service.IVoucherOrderService;
import com.cse.utils.RedisIdWorker;
import com.cse.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.cse.constants.RedisConstants.ORDER_KEY_PREFIX;
import static com.cse.constants.RedisConstants.ORDER_SHOP_KEY_PREFIX;
import static com.cse.constants.SystemConstants.STOCK_NULL;
import static com.cse.constants.SystemConstants.USER_AREADY_BUY;

@Slf4j
@Service
@RequiredArgsConstructor
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    private final RedisIdWorker redisIdWorker;
    private final ISeckillVoucherService seckillVoucherService;
    private final StringRedisTemplate stringRedisTemplate;
    private final RedissonClient redissonClient;
    private IVoucherOrderService proxy;
    private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();
    private final VoucherOrderMapper voucherOrderMapper;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        //在静态代码块理初始化脚本
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    @PostConstruct//当前类初始化完成之后执行
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable{
        String queueName="stream.orders";
        public void run() {
            while(true){
                try {
                    //1获取消息队列中的订单信息 XREADGROUP GROUP 组g1 消费者c1 COUNT 1 BLOCK 2000 STREANS streams.order >标识坠井一条消息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2判断消息是否获取成功
                    if (list ==null||list.isEmpty()) {
                        //失败继续下一次循环
                        continue;
                    }
                    //3解析消息中的订单信息
                    MapRecord<String,Object,Object> record=list.get(0);
                    Map<Object,Object> values=record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //4获取成功，成功下单
                    handleVoucherOrder(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            String queueName="stream.orders";
            while(true){
                try {
                    //1获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREANS streams.order 0
                    List<MapRecord<String,Object,Object>> list=stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1","c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2判断消息是否获取成功
                    if (list ==null || list.isEmpty()) {
                        //失败out
                        break;
                    }
                    //3解析消息中的订单信息
                    MapRecord<String,Object,Object> record=list.get(0);
                    Map<Object,Object> values=record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //4获取成功，成功下单
                    handleVoucherOrder(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException interruptedException) {
//                  log.error("系统休眠",ex);
                  interruptedException.printStackTrace();

                    }
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户
        Long userId = voucherOrder.getId();
        //用redisson获取锁
        RLock lock=redissonClient.getLock(ORDER_SHOP_KEY_PREFIX+userId);
        //获取锁
        boolean islock = lock.tryLock();
        if (!islock){
            //获取失败
            log.error(USER_AREADY_BUY);
            return ;
        }
        try {
        //获取代理对象
//            createVoucherOrder(voucherOrder);
            IVoucherOrderService proxy=(IVoucherOrderService) AopContext.currentProxy();
//          用当前代理对象调用方法不用this 避免spring管理失败事务不成功
            proxy.createVoucherOrder(voucherOrder);

        } finally {
            //释放锁
            lock.unlock();
        }
    }


    @Transactional
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //orderid
        long orderId = redisIdWorker.nextId(ORDER_KEY_PREFIX);
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );
        //2.判断结果为0
        if  (result==null) {
            //2.1为null，代表购买失败
            return Result.fail(USER_AREADY_BUY);
        }

        int r = result.intValue();
        if (r!=0) {
            //2.1不为0，代表没有购买资格
            return Result.fail(r==1?STOCK_NULL:USER_AREADY_BUY);
        }
        //获取IVoucherOrderService当前代理对象，被spring创建是带有事务的 需暴露代理对象
        proxy=(IVoucherOrderService) AopContext.currentProxy();
        //3.返回订单id
        return Result.ok(orderId);
    }

    @Transactional
    public  void createVoucherOrder(VoucherOrder voucherOrder) {
        //获取userid 一人一单
        Long userId =voucherOrder.getUserId();
        Long voucherId=voucherOrder.getVoucherId();
        //按照值来加锁 用户id值一样锁就一样
            //判断该用户购买相应id的秒杀卷的数量
            int count = query().eq("user_id", userId)
                    .eq("voucher_id", voucherId).count();
            //优惠卷不为零
            if (count > 0) {
                log.error(USER_AREADY_BUY);
                return ;
            }
            //扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id",voucherId)
                    //乐观锁解决超买问题
                    .gt("stock", 0)
                    .update();
            if (!success) {

                log.error(STOCK_NULL);

                return ;
            }
        save(voucherOrder);
        }
}
